package com.alibaba.travel.article.interceptor;

import com.alibaba.travel.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: where
 * @Date: 2023/02/28/8:48
 * @Description: 用户是否登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    public static ThreadLocal<Long> userIdLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、从请求体中获取token
        String token = (String) request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            return true;
        }
        // 2、调用member模块的判断方法 -- 传入token 得到userId
        // 3、通过userId 获取redis内的用户信息 （也可以存入threadLocal -- 记住用完后删除）

        Claims claims = JwtUtil.parseJWT(token);
        String subject = claims.getSubject();
        userIdLocal.set(Long.valueOf(subject));
        return true;
    }
}
